<?php
/*
* Author: Nguyen Hai Nam
* Module: Admin
* Desc	: Introduce pick.vn and sidle pic
* Date	: 12/12/2011
*/
class Config_ModulesModule extends Pick_Core_Module{
	
	public $authentication = 1;
    private $language;


    function Config_ModulesModule(){
		
		parent::Pick_Core_Module();
		$this->theme = "admin";		
		# Languages
		$languages = new Pick_Core_Languages();
        $this->language = $languages;
		$objectLanguages = "";
		$objectLanguages = $languages->getObjects(1, 'status = 1', array('position'=>'ASC'), '');
		if($objectLanguages){
			$objectLanguages = $objectLanguages['data'];	
		}#endif
		$this->template->assign("objectLanguages", $objectLanguages);
        
        // Get Path for this module
        $this->template->assign('arrayParentPath', $this->getArrayParentPath());
	}
	public function getContent(){
		
		$act = $this->request->element('act', "list");
		$this->template->assign('act', $act);
		
		// Process ajax for postion cof module
		if($act == "position"){
			$modules = new Pick_Core_Modules();
			$oId = $this->request->element('id','');
			$val = $this->request->element('val','');
			$arrData = array('position'=>$val);
			echo $modules->updateData($arrData, $oId);
			die;
		}
		if($act == "add"){
			$this->addAction();
		}else{
			$this->listAction();	
		}
		
	}
	public function listAction(){
		
		$modulestype	= new Pick_Core_ModulesType();
		$modules 		= new Pick_Core_Modules();
		$actions 		= new Pick_Core_Actions();
		
		$actions->setInfoAction($modules, $this->request);
		
		$items_per_pages = DEFAULT_ADMIN_ROWS_PER_PAGE;
		$infoText = '';
		$infoClass = 'infoText';
		
		# Read parameters from request
		$plus 			= $this->request->element('plus','');
		$pid 			= $this->request->element('pid','');
		$typeid			= $this->request->element('typeid','');
		$searchTerms 	= $this->request->element('searchTerms','');
		$searchStatus 	= $this->request->element('searchStatus','');
		$page 			= $this->request->element('page',1);
		$orderBy 		= $this->request->element('orderBy', 'position');
		$orderDir 		= $this->request->element('orderDir', 'ASC');
		$ajax 			= $this->request->element('ajax', false);
		$theme 			= $this->request->element('theme', '');
		// Call ajax for theme
		if($ajax == true && $theme != ''){
			$strOption = optionLayout($theme, '');
			echo $strOption;
			exit();
		}
		
		# Control plus action
		if($plus){
			$actions->auto($plus);
			$infoText 	= $actions->getInfoAction();
			$infoClass 	= "errorText";		
		}
		
		$objectMenu = $modulestype->getObjects(1, '1=1', array('position'=>'ASC'),'');
		if(isset($objectMenu['data'])) $objectMenu = $objectMenu['data'];
		
		# Lay menu mac dinh
		if(!$typeid){
			if(is_array($objectMenu)){
				$typeid = $objectMenu[0]->getField('id');
			}
		}
		
		if($pid == "")
			$pid = 0;	

		# Menu
		$this->getMenu();
		
		# Build search condition
        $languages = new Pick_Core_Languages();
        $langDefault  = $languages->getDefaultLanguage();
		$searchCond = "1=1";
		if($pid != '' ) 			$searchCond .= " AND cid = $pid"; else $searchCond .= " AND cid = 0";
		if($typeid != '') 			$searchCond .= " AND typeid = $typeid";
		if($searchStatus != '') 	$searchCond .= " AND status = '$searchStatus'";
		if($searchTerms != '') 		$searchCond .= " AND (".$langDefault."_name LIKE '%".$searchTerms."%' OR code LIKE '%".$searchTerms."%')";

		# Get all categories object and pass to template
		$listObjects = $modules->getObjects($page, $searchCond, array('position' => 'ASC'));

		# Generate status combobox for Search form
		$listStatus = optionStatus($searchStatus);
		
		# Pass some variables to template
		$this->template->assign('pid',$pid);
		$this->template->assign('page',$page);
		$this->template->assign('typeid',$typeid);			
		$this->template->assign('listStatus',$listStatus);
		$this->template->assign('listObjects',$listObjects);
		$this->template->assign('searchTerms',$searchTerms);
		$this->template->assign('searchStatus',$searchStatus);
		$this->template->assign('orderBy',$orderBy);
		$this->template->assign('orderDir',$orderDir);
		$this->template->assign('infoText',$infoText);
		$this->template->assign('infoClass',$infoClass);

	}
	
	public function addAction(){
		
		$modulestype	= new Pick_Core_ModulesType();
		$modules 		= new Pick_Core_Modules();
		$objectInfo 	= new Pick_Core_ModulesInfo();
		$textfilter 	= new Pick_Data_TextFilter();
		
		$pid = $this->request->element('pid','');
		$typeid = $this->request->element('typeid','');
		$oId = $this->request->element('oId','');
		$plus = $this->request->element('plus','');
		$infoText = '';
		$infoClass = '';
		
		# Read parameters from request
		$arrayFieldFromMySQL = $modules->getListFields();
		$object = $modules->getObject($oId);
		
		$plugins = array();
		if(is_object($object) && $this->request->post('plus')==""){
			foreach($arrayFieldFromMySQL as $fieldName){
				$fields[$fieldName] = $object->getField($fieldName);
			}#endforeach
			// string plugin get from database
			$strPlugin = $object->getField('plugin');
			$strPluginDefault = explode(",", $strPlugin);
			$plugins = $this->request->element('plugin', $strPluginDefault);
		}else{
			foreach($arrayFieldFromMySQL as $fieldName){
				$fields[$fieldName] = $this->request->element($fieldName,'');
			}#endforeach
			$plugins = $this->request->element('plugin', '');
		}
		
		# Modify item of array
		$fields['plugin'] = implode(",", $plugins);
		$modulestype = new Pick_Core_ModulesType();
		$objectMenu = $modulestype->getObjects(1, '1=1', array('position'=>'ASC'),'');
		if($objectMenu) $objectMenu = $objectMenu['data'];
		$this->template->assign("objectMenu", $objectMenu);	
		
		# Lay menu mac dinh
		if(!$typeid){
			if(is_array($objectMenu)){
				$typeid = $objectMenu[0]->getField('id');
			}
		}
		
		if($pid == "")
			$pid = 0;
		$this->template->assign('typeid',$typeid);
		
		# Menu
		$menu = $this->getMenu();
		
		# Put data into object
		$objectInfo->setArrayField($fields);
		$this->template->assign("objectInfo", $objectInfo);
		
		# Truy du lieu qua template
		foreach($arrayFieldFromMySQL as $fieldName){
				$this->template->assign($fieldName, $objectInfo->getField($fieldName));
		}#endforeach
		$listStatus = optionStatus($objectInfo->getField('status'), DEFAULT_ADMIN_LANGUAGE);
		$this->template->assign("listStatus",$listStatus);
		$listCategory = $modules->getOptionAllLevelModule(0, $objectInfo->getField('cid'), array('position' => 'ASC'), $typeid);
		$this->template->assign("listCategory",$listCategory);
		# Theme
		$listTheme = optionTemplates($objectInfo->getField('theme'));
		$this->template->assign("listTheme",$listTheme);
		# Layout
		$listLayout = optionLayout($objectInfo->getField('theme'), $objectInfo->getField('layout'));
		$this->template->assign("listLayout",$listLayout);		
		# Plugin
		$arrPlugin = array();
		$pluginsDir = ROOT_PATH.'/plugins/';
		if ($handle = opendir($pluginsDir)) {
			while (false !== ($entry = readdir($handle))) {
				$filePHP = file_exists(strtolower($pluginsDir.$entry."/".$entry.'.plugin.php'));
				$fileTPL = file_exists(strtolower($pluginsDir.$entry."/".$entry.'.temp.html'));
				if($filePHP&&$fileTPL){
					$infoPlugin = array();
					// Get infor of plugins
					$contentPlugin = file_get_contents($pluginsDir.$entry."/".$entry.'.plugin.php');
					preg_match('/namePlugin = "([a-zA-Z0-9]*)"/', $contentPlugin, $matchesName);			
					if(isset($matchesName[1])) $infoPlugin['namePlugin'] = $matchesName[1];
					preg_match('/descriptionPlugin = "([a-zA-Z0-9\s]*)"/', $contentPlugin, $matchesName);			
					if(isset($matchesName[1])) $infoPlugin['descriptionPlugin'] = $matchesName[1];
		
					if(isset($infoPlugin['namePlugin'])&&isset($infoPlugin['descriptionPlugin'])){
						$arrPlugin[] = $infoPlugin;
					}
				}
			}
			closedir($handle);	
		}
		$this->template->assign("arrPlugin",$arrPlugin);
		$this->template->assign("plugins",$plugins);
		
		# Begin process data
		if($_POST && $plus == 'saveItem') {
			# Validation
			$validate 	= new Pick_Data_Validate();
			$validatemess = $this->validateData($this->request, $validate);
				
			if($validatemess == '') {
				/* Test if it's exists then can't add theme more'' */
				$objModule = "";
				
				if($oId<=0){
					$objModule = $modules->checkDataExits($fields);
				}               
				if($objModule){
					$infoText = $this->l('item_saved_error');
					$infoClass = "errorText";			
				}else{
					$ok = $modules->updateData($objectInfo->getArrayField(),$oId);
					$infoText = $validatemess;
					if($ok){
						$infoText = $this->l('item_save_ok');
						$infoClass = "InfoText";
						$oId = $oId?$oId:mysql_insert_id();			
					}
				}
				
			}else {
				$infoText = $this->l('error').":<br />".$validatemess;
				$infoClass = "errorText";
			}
		}
		$this->template->assign("oId",$oId);
		$this->template->assign("infoText",$infoText);
		$this->template->assign("infoClass",$infoClass);
		$this->template->assign("menu",$menu);

	}		
	public function getMenu(){
		
		# Lấy thông tin chuyen muc từ $pid;
		$pid = $this->request->element('pid', '');
		$typeid = $this->request->element('typeid', '');
		$modulestype = new Pick_Core_ModulesType();
		$objectMenu = $modulestype->getObjects(1, '1=1', array('position'=>'ASC'),'');
		if($objectMenu) $objectMenu = $objectMenu['data'];
		$this->template->assign("objectMenu", $objectMenu);	
		
		# Lay menu mac dinh
		if(!$typeid){
			if(is_array($objectMenu)){
				$typeid = $objectMenu[0]->getField('id');
			}
		}
		
		if($pid == "")
			$pid = 0;
		$this->template->assign('typeid',$typeid);
		$this->template->assign('pid',$pid);
	}
	function validateData($request, $validate) {
		$infoText = '';
		$infoText .= $validate->validString($this->l('code'),$request->element('code'));
        $arrLanguage = $this->language->getObjects(1, '`status`=1');
        foreach( $arrLanguage['data'] as $objLanguage){
            $infoText .= $validate->validString($this->l($objLanguage->getField('code').'_name'),$request->element($objLanguage->getField('code').'_name'));
        }
		return $infoText;
	}	
}